package cn.whitecao.contentcenter.service;

import cn.whitecao.contentcenter.dao.RocketmqTransactionLogMapper;
import cn.whitecao.contentcenter.dao.ShareMapper;
import cn.whitecao.contentcenter.domain.dto.content.ShareAuditDTO;
import cn.whitecao.contentcenter.domain.dto.content.ShareDTO;
import cn.whitecao.contentcenter.domain.dto.messaging.UserAddBonusMsgDTO;
import cn.whitecao.contentcenter.domain.dto.user.UserDTO;
import cn.whitecao.contentcenter.entity.RocketmqTransactionLog;
import cn.whitecao.contentcenter.entity.Share;
import cn.whitecao.contentcenter.feignclient.UserCenterFeignClient;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.openfeign.SpringQueryMap;
import org.springframework.http.ResponseEntity;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.UUID;

@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ShareService {
    private final ShareMapper shareMapper;
    private final RestTemplate restTemplate;
    private final DiscoveryClient discoveryClient;
    private final UserCenterFeignClient userCenterFeignClient;
    private final RocketMQTemplate rocketMQTemplate;
    private final RocketmqTransactionLogMapper rocketmqTransactionLogMapper;

    public Share auditById(){
//        this.rocketMQTemplate.convertAndSend("add-bonus",
//                UserAddBonusMsgDTO.builder().userId(1).bonus(50).build());

        String transactionId = UUID.randomUUID().toString();
        this.rocketMQTemplate.sendMessageInTransaction("tx-add-bonus-group", "add-bonus",
                MessageBuilder
                        .withPayload(UserAddBonusMsgDTO.builder().userId(1).bonus(50).build())
                        .setHeader(RocketMQHeaders.TRANSACTION_ID, transactionId).setHeader("share_id",777)
                        .build(),
                new ShareAuditDTO());
        return null;
    }

    public void auditByIdWithRocketMqLog(Integer id,ShareAuditDTO shareAuditDTO,String transactionId){
        //this.auditById();

        RocketmqTransactionLog transactionLog = new RocketmqTransactionLog();
        transactionLog.setTransactionId(transactionId);
        transactionLog.setLog("审核分享");
        this.rocketmqTransactionLogMapper.insert(transactionLog);
        log.info("添加积分");

    }





    public UserDTO queryTest(@SpringQueryMap UserDTO userDTO ){
        return userCenterFeignClient.query(userDTO);
    }
    @Async
    @Transactional
    public void asyncTest(@SpringQueryMap UserDTO userDTO ){
        System.out.println(Thread.currentThread().getName());
    }
    public ShareDTO findById(Integer id) {
        // 获取分享详情
        Share share = this.shareMapper.selectById(id);

        // 发布人id
        Integer userId = share.getUserId();

        // 强调：
        // 了解stream --> JDK 8
        // lambda表达式
        // functional --> 函数式编程
        // 用户中心所有实例的信息
        List<ServiceInstance> instances = discoveryClient.getInstances("user-center");
//        String targetURL = instances.stream()
//                // 数据变换
//                .map(instance -> instance.getUri().toString() + "/users/{id}")
//                .findFirst()
//                .orElseThrow(() -> new IllegalArgumentException("当前没有实例！"));
//
//        log.info("请求的目标地址：{}", targetURL);
//        UserDTO userDTO = this.restTemplate.getForObject(
//                targetURL,
//                UserDTO.class, userId
//        );

//        UserDTO userDTO = this.restTemplate.getForObject(
//                "http://user-center/users/{userId}",
//                UserDTO.class, userId
//        );
        //通过feign的方式来请求user-center
        UserDTO userDTO = userCenterFeignClient.findById(userId);



        ShareDTO shareDTO = new ShareDTO();
        // 消息的装配
        BeanUtils.copyProperties(share, shareDTO);
        shareDTO.setWxNickname(userDTO.getWxNickname());
        return shareDTO;
    }

//    public static void main(String[] args) {
//        RestTemplate restTemplate = new RestTemplate();
//        // 用HTTP GET方法去请求，并且返回一个对象
//        ResponseEntity<String> forEntity = restTemplate.getForEntity(
//                "http://localhost:8080/users/{id}",
//                String.class, 2
//        );
//
//        System.out.println(forEntity.getBody());
//        // 200 OK
//        // 500
//        // 502 bad gateway...
//        System.out.println(forEntity.getStatusCode());
//    }
}